package com.tanhua.manage.msg;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.manage.enums.AutoAuditStateEnum;
import com.tanhua.manage.enums.LogTypeEnum;
import com.tanhua.manage.enums.PublishAuditStateEnum;
import com.tanhua.manage.pojo.PublishAuditLog;
import com.tanhua.manage.pojo.PublishInfo;
import com.tanhua.manage.service.HuaWeiUGCService;
import com.tanhua.manage.service.PublishAuditLogService;
import com.tanhua.manage.service.PublishInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RocketMQMessageListener(topic = "tanhua-quanzi",
        consumerGroup = "tanhua-quanzi-audit-consumer")
@Slf4j
public class PublishMsgConsumer implements RocketMQListener<String> {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private PublishInfoService publishInfoService;

    @Autowired
    private HuaWeiUGCService huaWeiUGCService;

    @Value("${tanhua.autoAudit}")
    private Boolean autoAudit;

    @Autowired
    private PublishAuditLogService publishAuditLogService;

    /**
     * 1-发动态，2-浏览动态， 3-点赞， 4-喜欢， 5-评论，6-取消点赞，7-取消喜欢
     *
     * @param msg
     */
    @Override
    public void onMessage(String msg) {
        JSONObject jsonObject = JSONUtil.parseObj(msg);
        Integer type = jsonObject.getInt("type");
        String publishId = jsonObject.getStr("publishId");
        Long date = jsonObject.getLong("date");
        Long userId = jsonObject.getLong("userId");

        //查询publish对象
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (ObjectUtil.isEmpty(publish)) {
            return;
        }

        //转发消息到tanhua-log
        Map<String, Object> logMsg = new HashMap<>();
        logMsg.put("userId", userId);
        logMsg.put("date", date);

        PublishInfo publishInfo = this.publishInfoService.queryByPublishId(publishId);
        if(type == 1 && publishInfo != null){
            return;
        }

        switch (type) {
            case 1:
                //发动态
                logMsg.put("type", LogTypeEnum.MOVEMENTS_ADD.getValue());

                processSavePublish(publish);

                break;
            case 3:
                //点赞
                logMsg.put("type", LogTypeEnum.MOVEMENTS_LIKE.getValue());

                publishInfo.setLikeCount(publishInfo.getLikeCount() + 1);

                break;
            case 4:
                //喜欢
                logMsg.put("type", LogTypeEnum.MOVEMENTS_LOVE.getValue());
                publishInfo.setLoveCount(publishInfo.getLoveCount() + 1);
                break;
            case 5:
                //评论
                logMsg.put("type", LogTypeEnum.MOVEMENTS_COMMENT.getValue());
                publishInfo.setCommentCount(publishInfo.getCommentCount() + 1);
                break;
            case 6:
                //取消点赞
                logMsg.put("type", LogTypeEnum.MOVEMENTS_UNLIKE.getValue());
                publishInfo.setLikeCount(publishInfo.getLikeCount() - 1);
                break;
            case 7:
                //取消喜欢
                logMsg.put("type", LogTypeEnum.MOVEMENTS_UNLOVE.getValue());
                publishInfo.setLoveCount(publishInfo.getLoveCount() - 1);
                break;
            default:
                return;
        }

        if(null != publishInfo){
            this.publishInfoService.updateById(publishInfo);
        }

        //转发消息
        this.rocketMQTemplate.convertAndSend("tanhua-log", logMsg);

    }

    /**
     * 动态发布
     * 1.保存PublishInfo数据
     * 2.进行机审
     *
     * @param publish
     */
    private void processSavePublish(Publish publish) {
        String publishId = publish.getId().toString();
        //校验是否已经处理过
        PublishInfo publishInfo = this.publishInfoService.queryByPublishId(publishId);

        if (ObjectUtil.isNotEmpty(publishInfo)) {
            return;
        }

        publishInfo = new PublishInfo();
        publishInfo.setCreateDate(publish.getCreated());
        publishInfo.setPublishId(publishId);
        publishInfo.setUserId(publish.getUserId());

        //内容审核，先进行机审，再人工审核
        if (autoAudit) {
            //审核文本和图片
            AutoAuditStateEnum textContentCheck = this.huaWeiUGCService.textContentCheck(publish.getText());
            AutoAuditStateEnum imageContentCheck = this.huaWeiUGCService.imageContentCheck(Convert.toStrArray(publish.getMedias()));

            if (textContentCheck == AutoAuditStateEnum.REVIEW || imageContentCheck == AutoAuditStateEnum.REVIEW) {
                //等待人工审核
                publishInfo.setState(PublishAuditStateEnum.WAIT_MAUL.getValue());
            } else if (textContentCheck == AutoAuditStateEnum.PASS && imageContentCheck == AutoAuditStateEnum.PASS) {
                //自动审核通过
                publishInfo.setState(PublishAuditStateEnum.AUTO_PASS.getValue());
            } else {
                //自动审核拒绝
                publishInfo.setState(PublishAuditStateEnum.AUTO_BLOCK.getValue());
            }

        } else {
            //等待人工审核
            publishInfo.setState(PublishAuditStateEnum.WAIT_MAUL.getValue());
        }

        //保存数据
        this.publishInfoService.save(publishInfo);

        if (autoAudit) {
            PublishAuditLog publishAuditLog = new PublishAuditLog();
            publishAuditLog.setPublishId(publishId);
            publishAuditLog.setSourceState(PublishAuditStateEnum.WAIT.getValue());
            publishAuditLog.setTargetState(publishInfo.getState());

            this.publishAuditLogService.save(publishAuditLog);
        }
    }
}
